//
//  MessageViewController.m
//  TotalDemo
//
//  Created by gujian on 16/5/30.
//  Copyright © 2016年 gujian. All rights reserved.
//

#import "MessageViewController.h"
#import <MessageUI/MessageUI.h>

typedef NS_ENUM(NSUInteger, BtnTag) {
    BtnTag_SMS = 301,
    BtnTag_MMS,
    BtnTag_Mail,
    BtnTag_Hide
    
};

@interface MessageViewController ()<MFMessageComposeViewControllerDelegate,MFMailComposeViewControllerDelegate>

@property (nonatomic, strong) MFMessageComposeViewController *messageViewController;
@property (nonatomic, strong) MFMailComposeViewController *mailViewController;

@end

@implementation MessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addNotification];
    [self initSubviews];
    self.view.backgroundColor = [UIColor randomColor];
    
    //禁用侧滑手势
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

- (void)initSubviews
{
    CGFloat btnWidth = 100;
    CGFloat btnHeight = 34.0;
    
    CGFloat offY = 40.0;
    NSArray *btnTagArr = @[
                           @{@"TAG":@(BtnTag_SMS),@"TITLE":@"发送SMS"},
                           @{@"TAG":@(BtnTag_MMS),@"TITLE":@"发送MMS"},
                           @{@"TAG":@(BtnTag_Mail),@"TITLE":@"发送邮件"},
                           @{@"TAG":@(BtnTag_Hide),@"TITLE":@"隐藏"}
                           ];
    
    for (NSDictionary *dict in btnTagArr) {
        NSInteger tag = [dict[@"TAG"] integerValue];
        NSString *btnTitle = dict[@"TITLE"];
        UIButton *btn = [TDViewUtils createCustomButton];
        btn.tag = tag;
        [btn setTitle:btnTitle forState:UIControlStateNormal];
        [btn setFrame:CGRectMake((SCREEN_WIDTH-btnWidth)/2.0, offY, btnWidth, btnHeight)];
        [btn addTarget:self action:@selector(sendMessageAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:btn];
        
        offY += (btnHeight + 20);
    }

    
    
    
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
    //禁用侧滑手势
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
}

- (void)dealloc
{
    [self removeNotification];
}

- (void)addNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleMessageNotification:) name:MFMessageComposeViewControllerTextMessageAvailabilityDidChangeNotification object:nil];
}

- (void)removeNotification
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MFMessageComposeViewControllerTextMessageAvailabilityDidChangeNotification object:nil];
}

#pragma mark - Button Action
- (void)sendMessageAction:(UIButton *)btn
{
  
    if (TARGET_IPHONE_SIMULATOR && btn.tag != BtnTag_Hide) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"不支持模拟器" preferredStyle:UIAlertControllerStyleAlert];
        __weak typeof(alertController) wsAlertController = alertController;
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            [wsAlertController dismissViewControllerAnimated:YES completion:nil];
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
        return;
    }
    
    MFMessageComposeViewController *messageController = [[MFMessageComposeViewController alloc] init];

    
    if (btn.tag == BtnTag_SMS || btn.tag == BtnTag_MMS) {
        messageController.messageComposeDelegate = self;
        _messageViewController = messageController;
        if ([MFMessageComposeViewController canSendText]) {
            //可发送sms
            messageController.recipients = @[@"18518366621"];
            messageController.subject = @"主题";
        }else
        {
            UIAlertController *alerController = [UIAlertController alertControllerWithTitle:@"" message:@"不支持发送短信" preferredStyle:UIAlertControllerStyleAlert];
            __weak typeof(UIAlertController) *wsAlertController = alerController;
            [alerController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                [wsAlertController dismissViewControllerAnimated:YES completion:nil];
            }]];
            [self presentViewController:alerController animated:YES completion:^{
                
            }];
            
            return;
        }
    }
    
    
    switch (btn.tag) {
        case BtnTag_SMS:
                messageController.body = @"测试发送SMS";
            break;
        case BtnTag_MMS:{
            
            messageController.body = @"测试发送MMS";
            if (![MFMessageComposeViewController canSendAttachments]) {
                break;
            }
            UIImage *img = [UIImage imageNamed:@"banner"];
            NSData *imgData = UIImagePNGRepresentation(img);
            [messageController addAttachmentData:imgData typeIdentifier:@"image/png" filename:@"banner.png"];

            NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"EmotionIcons" ofType:@"bundle"];
            NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];
            NSString *attachmentPath = [bundle pathForResource:@"emotion_magnifier@2x.png" ofType:nil];
            
            NSURL *url = [NSURL fileURLWithPath:attachmentPath];
            
            BOOL flag = [messageController addAttachmentURL:url withAlternateFilename:@"emotion_magnifier@2x.png"];
            if (flag) {
                LotLog(@"添加成功");
            }else
                LotLog(@"添加失败");
        }
            break;
        case BtnTag_Mail:
        {
            MFMailComposeViewController *mailViewController = [[MFMailComposeViewController alloc] init];
            if (![MFMailComposeViewController canSendMail]) {
                
                NSString *mailMessStr = @"mailto:gujian@360.cn&subject=测试&body=内容&cc=gujian@360.cn";
                mailMessStr = [mailMessStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:mailMessStr]];
                
                return;
                break;
            }
            mailViewController.mailComposeDelegate = self;
            [mailViewController setToRecipients:@[@"gujian@360.cn"]];
            [mailViewController setCcRecipients:@[@"gujian@360.cn"]];
            [mailViewController setBccRecipients:@[@"gujian@360.cn"]];
            [mailViewController setSubject:@"测试"];
            [mailViewController setMessageBody:@"哈哈哈" isHTML:NO];
            
            NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"EmotionIcons" ofType:@"bundle"];
            NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];
            NSString *attachmentPath = [bundle pathForResource:@"emotion_magnifier@2x.png" ofType:nil];
            NSData *imgData = [NSData dataWithContentsOfFile:attachmentPath];
            [mailViewController addAttachmentData:imgData mimeType:@"image/png" fileName:@"emotion"];
            
            
            
            _mailViewController = mailViewController;
        }
            break;
        
        case BtnTag_Hide:
            
//            if (_delegate && [_delegate respondsToSelector:@selector(shouldHideMessageViewController:)]) {
//                [_delegate shouldHideMessageViewController:self];
//            }
            
            if ([self.navigationController.viewControllers count] > 1) {
                [self.navigationController popViewControllerAnimated:YES];
            }else
                [self.navigationController dismissViewControllerAnimated:YES completion:nil];
            
            return;
            break;
    }
    
     LotLog(@"开始启动:%f",[[NSDate date] timeIntervalSince1970]);
    
    if (btn.tag != BtnTag_Hide) {
        if (btn.tag == BtnTag_Mail) {
            [self presentViewController:_mailViewController animated:YES completion:^{
                
                LotLog(@"启动完成:%f",[[NSDate date] timeIntervalSince1970]);
                
            }];
        }else
        {
            [self presentViewController:_messageViewController animated:YES completion:^{
                
                LotLog(@"启动完成:%f",[[NSDate date] timeIntervalSince1970]);
                
            }];
        }
    }
    

    
    
}

- (void)showAlertControllerWithMessage:(NSString *)messStr
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:messStr preferredStyle:UIAlertControllerStyleAlert];
    __weak typeof(alertController) wsAlertController = alertController;
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [wsAlertController dismissViewControllerAnimated:YES completion:nil];
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
}


#pragma mark - Notification Action

- (void)handleMessageNotification:(NSNotification *)noti
{
    LotLog(@"%@",noti);
    /**
     *Posted when the value returned by the canSendText class method has changed.
     
     *Upon receiving this notification, query its userInfo dictionary with the MFMessageComposeViewControllerTextMessageAvailabilityKey key. If the availability of text message sending has changed, your app should invalidate caches and update its user interface as appropriate.
     */
}

#pragma mark - MFMessageCompostViewControllerDelegate

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    
    [_messageViewController dismissViewControllerAnimated:YES completion:nil];
    
    NSString *messageStr;
    switch (result) {
        case MessageComposeResultSent:
            messageStr = @"已发送";
            break;
        case MessageComposeResultCancelled:
            messageStr = @"发送已取消";
            break;
        case MessageComposeResultFailed:
            messageStr = @"发送失败";
            break;
        default:
            break;
    }
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:messageStr preferredStyle:UIAlertControllerStyleAlert];
    __weak typeof(alertController) wsAlertController = alertController;
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [wsAlertController dismissViewControllerAnimated:YES completion:nil];
    }]];
    [self presentViewController:alertController animated:YES completion:^{
        
    }];
    
}

#pragma mark - MFMailComposeViewController delegate

- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    [_mailViewController dismissViewControllerAnimated:YES completion:nil];
    
    NSString *messStr = @"";
    
    switch (result) {
        case MFMailComposeResultSent:
            messStr = @"已发送";
            break;
        case MFMailComposeResultSaved:
            messStr = @"已保存为草稿";
            break;
        case MFMailComposeResultCancelled:
            messStr = @"已取消";
            break;
        case MFMailComposeResultFailed:
            messStr = @"失败";
            break;
        default:
            break;
    }
    
    [self showAlertControllerWithMessage:messStr];
}






















@end
